package com.yf.ability.upload.providers.local.service.impl;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.yf.ability.config.dto.CfgPropDTO;
import com.yf.ability.config.enums.ConfigType;
import com.yf.ability.config.enums.ProviderType;
import com.yf.ability.config.service.CfgPropService;
import com.yf.base.api.api.ApiRest;
import com.yf.base.api.exception.ServiceException;
import com.yf.ability.Constant;
import com.yf.ability.upload.providers.local.config.LocalConfig;
import com.yf.ability.upload.providers.local.dto.UploadReqDTO;
import com.yf.ability.upload.providers.local.dto.UploadRespDTO;
import com.yf.ability.upload.providers.local.service.LocalUpService;
import com.yf.ability.upload.providers.local.utils.OssUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.tika.Tika;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 文件上传业务类
 * @author bool
 * @date 2019-07-30 21:02
 */
@Log4j2
@Service
public class LocalUpServiceImpl implements LocalUpService {


    @Autowired
    private CfgPropService cfgPropService;


    @Override
    public UploadRespDTO upload(UploadReqDTO reqDTO) {

        // 查找上传配置
        LocalConfig conf = this.getConfig();

        // 文件内容
        MultipartFile file = reqDTO.getFile();

        // 上传文件夹
        String fileDir = conf.getLocalDir();

        // 真实物理地址
        String fullPath;

        try {
            // 新文件
            String filePath = OssUtils.processPath(file);
            // 文件保存地址
            fullPath = fileDir + filePath;
            // 创建文件夹
            OssUtils.checkDir(fullPath);
            System.out.println("存储地址是："+fullPath);

            // 上传文件
            FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(fullPath));
            System.out.println("回调地址："+this.generateResult(conf, filePath));

            return this.generateResult(conf, filePath);

        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("文件上传失败："+e.getMessage());
        }
    }


    @Override
    public String upload(String localFile) {
        // 查找上传配置
        LocalConfig conf = this.getConfig();

        // 上传文件夹
        String fileDir = conf.getLocalDir();

        // 真实物理地址
        String fullPath;

        try {

            FileInputStream is = new FileInputStream(localFile);

            // 新文件
            String filePath = OssUtils.renameFile(localFile);
            // 文件保存地址
            fullPath = fileDir + filePath;
            // 创建文件夹
            OssUtils.checkDir(fullPath);
            // 上传文件
            FileCopyUtils.copy(is, new FileOutputStream(fullPath));

            return conf.getUrl() + Constant.FILE_PREFIX + filePath;

        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("文件上传失败："+e.getMessage());
        }
    }

    @Override
    public boolean delete(String fileURI) {
        // 查找上传配置
        LocalConfig conf = this.getConfig();

        // 获取真实的文件路径
        String filePath = this.getRealPath(conf, fileURI);
        File file = new File(filePath);

        if(!file.exists()){
            return true;
        }

        // 删除文件
        return FileUtil.del(file);
    }

    @Override
    public boolean delete(List<String> fileURIs) {
        // 查找上传配置
        LocalConfig conf = this.getConfig();

        for (String fileURI : fileURIs) {
            // 获取真实的文件路径
            String filePath = this.getRealPath(conf, fileURI);
            File file = new File(filePath);

            if(!file.exists()){
                continue;
            }

            // 删除文件
            FileUtil.del(file);
        }
        return true;
    }


    @Override
    public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 查找上传配置
        LocalConfig conf = this.getConfig();

        // 获取真实的文件路径
        String filePath = this.getRealPath(conf, request.getRequestURI());
        File file = new File(filePath);

        if(!file.exists()){
            throw new ServiceException("文件不存在！");
        }

        // 断点下载
        this.chunkDownload(request, response, file);
    }

    /**
     * 获取配置文件
     * @return
     */
    @Override
    public LocalConfig getConfig(){
        CfgPropDTO dto = cfgPropService.detail(ConfigType.UPLOAD, ProviderType.LOCAL);
        LocalConfig cfg = JSON.parseObject(dto.getData(), LocalConfig.class);
        return cfg;
    }


    /**
     * 构造返回
     * @param fileName
     * @return
     */
    private UploadRespDTO generateResult(LocalConfig conf, String fileName) {

        //获取加速域名
        String domain = conf.getUrl();

        // 返回结果
        return new UploadRespDTO(domain + Constant.FILE_PREFIX + fileName);
    }


    /**
     * 获取真实物理文件地址
     * @param uri
     * @return
     */
    public String getRealPath(LocalConfig conf, String uri){

        String regx = Constant.FILE_PREFIX+"(.*)";

        // 查找全部变量
        Pattern pattern = Pattern.compile(regx);
        Matcher m = pattern.matcher(uri);
        if (m.find()) {
            String str = m.group(1);
            return conf.getLocalDir() + str;
        }

        return null;
    }

    /**
     * 支持以断点的方式输出文件，提供文件在线预览和视频在线播放
     * @param request
     * @param response
     * @param file
     * @throws IOException
     */
    public void chunkDownload(HttpServletRequest request,
                              HttpServletResponse response,
                              File file) throws IOException {

        //只读模式
        RandomAccessFile randomFile = new RandomAccessFile(file, "r");
        long contentLength = randomFile.length();
        String range = request.getHeader("Range");


        Tika tika = new Tika();
        String mimeType = tika.detect(file);
        response.setContentType(mimeType);
        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("Last-Modified", new Date().toString());

        // 断点下载支持
        long requestStart = 0, length=0;

        // 第一次只返回长度让浏览器来请求更多数据
        if (StringUtils.isEmpty(range)) {
            length = contentLength;
            response.setHeader("Content-length", contentLength + "");
        } else {
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            String[] ranges = range.split("=");
            long requestEnd = 0;
            if (ranges.length > 1) {
                String[] rangeData = ranges[1].split("-");
                requestStart = Long.parseLong(rangeData[0]);
                if (rangeData.length > 1) {
                    requestEnd = Long.parseLong(rangeData[1]);
                }
            }

            if (requestEnd > 0) {
                length = requestEnd - requestStart + 1;
                response.setHeader("Content-Range", "bytes " + requestStart + "-" + requestEnd + "/" + contentLength);
            } else {
                length = contentLength - requestStart;
                response.setHeader("Content-Range", "bytes " + requestStart + "-" + (contentLength - 1) + "/" + contentLength);
            }
            response.setHeader("Content-length", "" + length);
        }


        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        randomFile.seek(requestStart);
        byte [] buffer = new byte[1024];
        while (length > 0) {
            int len = randomFile.read(buffer);
            if (length < buffer.length) {
                out.write(buffer, 0, (int)length);
            } else {
                out.write(buffer, 0, len);
                if (len < buffer.length) {
                    break;
                }
            }
            length -= buffer.length;
        }
        out.flush();
        out.close();
        randomFile.close();
    }

}
